package com.bcsq.todolistdemo.video;

import android.content.Context;
import android.graphics.PixelFormat;
import android.hardware.Camera;
import android.media.AudioManager;
import android.media.MediaPlayer;
import android.media.MediaRecorder;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.util.Log;
import android.view.SurfaceHolder;
import android.view.SurfaceView;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.ProgressBar;
import android.widget.TextView;
import android.widget.Toast;


import com.bcsq.todolistdemo.R;
import com.bcsq.todolistdemo.util.Util;

import java.io.File;
import java.util.Calendar;

import androidx.appcompat.app.AppCompatActivity;

/**
 * 视频录制和上传
 */
public class VideoActivity extends AppCompatActivity implements SurfaceHolder.Callback, View.OnClickListener {
    private static final String TAG = "VideoActivity";
    private SurfaceView mSurfaceview;
    private ImageView mImageView;
    private Button mBtnStartStop;
    private Button mBtnPlay;
    private TextView mTextView;
    private boolean mIsPlay = false;//是否正在播放
    private boolean mStartedFlg = false;//是否正在录像
    private MediaPlayer mediaPlayer;//多媒体播放器
    private int text = 0;
    private MediaRecorder mRecorder;//多媒体录音
    private Camera mCamera;//相机
    private String path;//视频保存路径
    private SurfaceHolder mSurfaceHolder;
    private android.os.Handler handler = new android.os.Handler();//android.os  是一个移动设备，智能手机和平板电脑的操作系统
    private Context mContext;



    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        requestWindowFeature(Window.FEATURE_NO_TITLE);
        getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
                WindowManager.LayoutParams.FLAG_FULLSCREEN);// 设置全屏
        getWindow().setFormat(PixelFormat.TRANSLUCENT);

        setContentView(R.layout.activity_video);

        intView();
        SurfaceHolder holder = mSurfaceview.getHolder();
        holder.addCallback(this);
        holder.setType(SurfaceHolder.SURFACE_TYPE_PUSH_BUFFERS);//缓冲区

        mContext = this;
    }

    @Override
    protected void onResume() {
        super.onResume();
    }

    private void intView() {
        mSurfaceview = findViewById(R.id.surfaceview);
        mImageView =  findViewById(R.id.imageview);
        mBtnStartStop = findViewById(R.id.btnStartStop);
        mBtnPlay =  findViewById(R.id.btnPlayVideo);
        mTextView = findViewById(R.id.text);

        mBtnPlay.setOnClickListener(this);
        mBtnStartStop.setOnClickListener(this);
    }

    @Override
    public void surfaceCreated(SurfaceHolder holder) {
        mSurfaceHolder = holder;
    }

    @Override
    public void surfaceChanged(SurfaceHolder holder, int format, int width, int height) {
        mSurfaceHolder = holder;
    }

//    @Override
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.btnStartStop:
                if (mIsPlay) {//判断是否正在播放
                    stopMddiaPlayer();
                }
                //开始录像
                if (!mStartedFlg) {
                    startPlayer();
                }
                //停止
                else {
                    stopPlayer();
                    mStartedFlg = false;
                }
                break;

            case R.id.btnPlayVideo:
                if (mStartedFlg){
                    Toast.makeText(mContext, "正在录制，请结束录制再播放", Toast.LENGTH_SHORT).show();
                }else {
                    startPlayVideo();
                }
                break;
        }
    }

    /**
     * 停止媒体播放器
     */
    private void stopMddiaPlayer(){
        if (mediaPlayer != null) {//正在播放
            mIsPlay = false;
            mediaPlayer.stop();//停止媒体播放器
            mediaPlayer.reset();//重置媒体播放器
            mediaPlayer.release();//释放资源
            mediaPlayer = null;
        }
    }


    /**
     * 开始录像
     */
    private void startPlayer(){
        handler.postDelayed(runnable, 1000);
        mImageView.setVisibility(View.GONE);
        if (mRecorder == null) {//录音
            mRecorder = new MediaRecorder();
        }
        //后置摄像头：CAMERA_FACING_BACK   前置摄像头：CAMERA_FACING_FRONT
        mCamera = Camera.open(Camera.CameraInfo.CAMERA_FACING_BACK);
        if (mCamera != null) {
            mCamera.setDisplayOrientation(90);
            mCamera.unlock();
            mRecorder.setCamera(mCamera);
        }
        try {
            // 这两项需要放在setOutputFormat之前,设置音频和视频的来源
            mRecorder.setAudioSource(MediaRecorder.AudioSource.CAMCORDER);//摄录像机comcorder
            mRecorder.setVideoSource(MediaRecorder.VideoSource.CAMERA);//相机

            //输出格式 mp4
            mRecorder.setOutputFormat(MediaRecorder.OutputFormat.MPEG_4);

            //这两项需要放在setOutputFormat之后  设置编码器
            mRecorder.setAudioEncoder(MediaRecorder.AudioEncoder.AMR_NB);//音频编码格式
            mRecorder.setVideoEncoder(MediaRecorder.VideoEncoder.MPEG_4_SP);//视频编码格式

            mRecorder.setVideoSize(640, 480);//视频分辨率
            mRecorder.setVideoFrameRate(30);//帧速率
            mRecorder.setVideoEncodingBitRate(3 * 1024 * 1024);//视频清晰度
            mRecorder.setOrientationHint(90);//输出视频播放的方向提示
            //设置记录会话的最大持续时间（毫秒）
            mRecorder.setMaxDuration(100 * 1000);
            mRecorder.setPreviewDisplay(mSurfaceHolder.getSurface());//预览显示的控件

            path = Util.getSDPath();
            if (path != null) {
                File dir = new File(path);
                if (!dir.exists()) {//如果不存在这个文件，则创建。
                    dir.mkdir();
                }
                path = dir + File.separator + Util.getDate() + ".mp4";
                Log.i("chen", "文件存储路径：" + path );
                mRecorder.setOutputFile(path);//输出文件路径
                mRecorder.prepare();//准备
                mRecorder.start();//开始
                mStartedFlg = true;//录像开始
                mBtnStartStop.setText("结束录制");
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 停止录像
     */
    private void stopPlayer(){
        if (mStartedFlg) {
            handler.removeCallbacks(runnable);
            mRecorder.stop();//停止
            mRecorder.reset();//重置，设置为空闲状态
            mRecorder.release();//释放
            mRecorder = null;
            mBtnStartStop.setText("开始录制");
            text = 0;
            //释放相机
            if (mCamera != null) {
                mCamera.release();
                mCamera = null;
            }

            //将视频上传到服务器
            String postUrl = "http://39.104.85.239:8080/minio/uploadFile";
            ProgressBar post_progress = findViewById(R.id.post_progress);
            TextView post_text = findViewById(R.id.post_text);
            UploadVideo.post(postUrl, path, post_progress, post_text, new UploadVideo.UploadCallBackListener() {
                @Override
                public void onResult(String msg) {
                    Log.i(TAG, msg);
                }
            });
        }
    }

    /**
     * 开始播放
     */
    public void startPlayVideo(){
        if (mediaPlayer == null) {
            mediaPlayer = new MediaPlayer();
        }
        mediaPlayer.reset();
        if (path == null) {
            Toast.makeText(mContext, "暂无视频资源", Toast.LENGTH_SHORT).show();
        } else {
            mImageView.setVisibility(View.GONE);
            Uri uri = Uri.parse(path);
            mediaPlayer = MediaPlayer.create(mContext, uri);
            mediaPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC);
            mediaPlayer.setDisplay(mSurfaceHolder);//设置显示的控件
            try {
                mediaPlayer.prepare();
            } catch (Exception e) {
                e.printStackTrace();
            }

            mediaPlayer.start();
            mBtnPlay.setText("暂停");
            //监听播放器是否播放结束
            mediaPlayer.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
                @Override
                public void onCompletion(MediaPlayer mp) {
                    mImageView.setVisibility(View.VISIBLE);
                    mBtnPlay.setText("播放");
                    Toast.makeText(mContext, "播放完毕",
                            Toast.LENGTH_SHORT).show();
                }
            });

        }
    }



    @Override
    public void surfaceDestroyed(SurfaceHolder holder) {
        mSurfaceview = null;
        mSurfaceHolder = null;
//        handler.removeCallbacks(runnable);
        if (mRecorder != null) {
            mRecorder.release();
            mRecorder = null;
        }
        if (mCamera != null) {
            mCamera.release();
            mCamera = null;
        }
        if (mediaPlayer != null) {
            mediaPlayer.release();
            mediaPlayer = null;
        }
    }

    private Runnable runnable = new Runnable() {
        @Override
        public void run() {
            text++;
            mTextView.setText(text + "");
            handler.postDelayed(this, 1000);//休眠1秒
        }
    };








}


